from flask import current_app, jsonify
from flask import g
from flask import redirect
from flask import render_template
from flask import request
from flask import session

from info import constants
from info import db
from info.models import User, News, Category
from info.modules.profile import profile_blu
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET


# 个人主页主框架
@profile_blu.route('/info')
@user_login_data
def info():
    user = g.user
    if not user:
        return redirect('/')
    data = {
        "user": g.user.to_dict()
    }
    return render_template("news/user.html",data=data)


# 子框架－基本资料
@profile_blu.route('/base_info',methods=["POST","GET"])
@user_login_data
def base_info():
    user = g.user
    if request.method == "GET":
        return render_template("news/user_base_info.html",data=user)
    else:
        params_json = request.json
        nick_name = params_json.get("nick_name")
        signature = params_json.get("signature")
        gender = params_json.get("gender")
        if not all([nick_name, signature,gender ]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        if gender not in ["MAN", "WOMAN"]:
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        user.nick_name = nick_name
        user.signature = signature
        user.gender = gender
        try:
            db.session.commit()
        except Exception as ret:
            current_app.logger.error(ret)
            db.session.rollback()
            return jsonify(errno=RET.DBERR, errmsg="保存错误")
        return jsonify(errno=RET.OK, errmsg="保存成功")


# 子框架－个人头像
@profile_blu.route('/pic_info',methods=["GET","post"])
@user_login_data
def pic_info():
    user = g.user
    if request.method == "GET":
        return render_template('news/user_pic_info.html',data=g.user.to_dict())

    try:
        avatar_file = request.files.get("avatar").read()
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.PARAMERR, errmsg="参数读取错误")

    try:
        url = storage(avatar_file)
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.PARAMERR, errmsg="上传图片错误")
    user.avatar_url = url
    try:
        db.session.commit()
    except Exception as ret:
        current_app.logger.error(ret)
        db.session.rollback()
        return jsonify(errno=RET.PARAMERR, errmsg="保存图片错误")
    return jsonify(errno=RET.OK, errmsg="保存成功",data={"avatar_url":constants.QINIU_DOMIN_PREFIX+url})


# 子框架－密码修改
@profile_blu.route('/pass_info',methods=["GET","post"])
@user_login_data
def pass_info():
    user = g.user
    if request.method == "GET":
        return render_template('news/user_pass_info.html', data=user.to_dict())
    params_dict = request.json
    old_password = params_dict.get("old_password")
    new_password = params_dict.get("new_password")
    if not all([old_password,new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="原密码错误")
    user.password = new_password
    try:
        db.session.commit()
    except Exception as ret:
        current_app.logger.error(ret)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="密码修改失败")
    return jsonify(errno=RET.OK, errmsg="密码修改成功")


# 子框架－个人收藏
@profile_blu.route('/collected_info')
@user_login_data
def collected_info():
    user = g.user
    p = request.args.get("p",1)
    try:
        p = int(p)
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")
    current_page = 1
    total_page = 1
    collections = []
    try:
        paginates = user.collection_news.order_by(News.create_time).paginate(p,constants.USER_COLLECTION_MAX_NEWS,False)
        current_page = paginates.page
        total_page = paginates.pages
        collections = paginates.items
    except Exception as ret:
        current_app.logger.error(ret)
        # 增加本条代码会导致模板渲染出错，因为模板必须要接受data参数
        # return jsonify(errno=RET.DBERR, errmsg="查询错误")
    collection_dict = [collection.to_basic_dict() for collection in collections]
    data = {
        "current_page": current_page,
        "total_page": total_page,
        "collections": collection_dict
    }
    return render_template('news/user_collection.html',data=data)


# 子框架－新闻发布
@profile_blu.route('/news_release',methods=["GET","POST"])
@user_login_data
def news_release():
    if request.method == "GET":
        categories = []
        try:
            categories = Category.query.all()
        except Exception as ret:
            current_app.logger.error(ret)
        category_dict = [category.to_dict() for category in categories if category.id != 1]
        return render_template("news/user_news_release.html",data=category_dict)
    params_form = request.form
    title = params_form.get("title")
    category_id = params_form.get("category_id")
    digest = params_form.get("digest")
    index_image = request.files.get("index_image")
    content = params_form.get("content")
    if not all([title,category_id,digest,index_image,content]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        index_image = index_image.read()
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.PARAMERR, errmsg="图片加载失败")

    # 上传图片到七牛云
    try:
        key = storage(index_image)
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片失败")

    # 创建新闻模型
    news = News()
    news.title = title
    news.source = "个人发布"
    news.digest = digest
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.category_id = category_id
    news.user_id = g.user.id
    news.status = 1 # 代表审核中
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as ret:
        current_app.logger.error(ret)
        db.session.rollback()
        return jsonify(errno=RET.THIRDERR, errmsg="数据保存失败")
    return jsonify(errno=RET.OK, errmsg="数据保存成功，等待审核")


# 子框架－新闻列表
@profile_blu.route('/news_list')
@user_login_data
def news_list():
    page = request.args.get("page",1)
    try:
        page = int(page)
    except Exception as ret:
        current_app.logger.error(ret)
        page = 1
    user_news_list = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id == g.user.id).paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
        current_page = paginate.page
        total_page = paginate.pages
        user_news_list = paginate.items
    except Exception as ret:
        current_app.logger.error(ret)

    user_news_dict = [news.to_review_dict() for news in user_news_list]
    data = {
        "current_page": current_page,
        "total_page": total_page,
        "user_news_dict":user_news_dict
    }
    return render_template("news/user_news_list.html",data=data)